import {HttpException, HttpStatus, Inject, Injectable} from "@nestjs/common";
import {SysUserService} from "../service/SysUserService";
import {LoginDTO} from "./dto/LoginDTO";
import {Result} from "../common/Result";
import {JwtConstant} from "../common/constant/JwtConstant";
import {SysUser} from "../entity/SysUser";
import { JwtService } from '@nestjs/jwt';
import {ServerErrorException} from "../common/exception/ServerErrorException";

/**
 * 登录认证
 */
@Injectable()
export class AuthService {
    @Inject()
    private sysUserService: SysUserService;

    @Inject()
    private jwtService: JwtService;

    /**
     * 登录
     * @param user
     */
    async doLogin(user: LoginDTO) {
        console.log('登录步骤1：登录请求');
        const result = await this.validateUser(user);
        if (!result.success) {
            return result;
        }
        return this.certificate(result.data);
    }

    /**
     * 校验用户
     * @param user
     */
    async validateUser(user: LoginDTO): Promise<Result<any>> {
        console.log('登录步骤2：校验用户');
        let sysUser = new SysUser();
        sysUser.username = user.username;
        let one = await this.sysUserService.findDetails(sysUser);
        if (!one) {
            return Result.failed('账号或密码错误-0!')
        } else {
            let encryptPassword = JwtConstant.encryptPassword(user.password);
            let {password, ...data} = one;
            return encryptPassword == one.password ?  Result.success('登录成功', data) : Result.failed('账号或密码错误!') ;
        }
    }

    /**
     * token签发
     * @param user
     */
    async certificate(user: SysUser) {
        // const payload = {
        //     sub: user.id,
        //     username: user.username,
        //     name:
        // }
        console.log('登录步骤3：token签发');
        let token ;
        let roles = user.roles.map(item => {
            return  item.roleId;
        })
        const payload = {...user, sub: user.id, roles};
        try {
            token = this.jwtService.sign(payload);
        } catch (e) {
            throw new ServerErrorException();
        }
        return Result.success('登录成功!', {...payload, token});
    }
}
